<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" label-width="90">
          <el-form-item label="分包方名称：" prop="packageName">
            <el-input clearable placeholder="请输入分包方名称" v-model="queryParams.packageName" maxlength="100"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-row>
            <el-col :span="18">
              <el-form-item label="所在地区：">
                <City @queryParam="cityQueryParam" :id="'left'" ref="areaRef" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 机构列表盒子 -->
      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">分包方列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="margin-bottom: 5px">
            <el-button type="success" link style="color: var(--theme-deep-color)" @click="handleAddOrg">
              <el-icon color="#229A35">
                <Plus />
              </el-icon>新增
            </el-button>
          </el-row>
        </el-row>
        <el-table class="business" v-loading="loading" :row-class-name="tableRowClass" :data="orgTable" ref="mainTableRef"
          @row-click="rowClick" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="分包方名称" width="270" align="center" prop="packageName" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="success" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </el-card>
    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-form label-width="130px" :model="form" :rules="rules" ref="orgRef">
        <div>
          <el-row style="margin-bottom: 5px">
            <el-col :span="22">
              <p class="pinformation">基础信息</p>
            </el-col>
            <el-col :span="2">
              <el-button type="success" size="small" @click="submitForm()">保存</el-button>
            </el-col>
          </el-row>
          <el-form-item label="分包机构名称：" prop="packageName">
            <el-input placeholder="请输入分包机构名称" v-model="form.packageName" clearable maxlength="100" />
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="公司地址：" prop="areaCode">
                <City @queryParam="cityQueryParam" :id="'right'" @areaCode="areaCode" :viewForm="viewCity" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="详细地址：" prop="packageAddress">
                <el-input clearable placeholder="请输入详细地址" v-model="form.packageAddress" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="法人姓名：" prop="personName">
                <el-input placeholder="请输入法人姓名" v-model="form.personName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="法人联系方式：" prop="personPhonenumber">
                <el-input clearable placeholder="法人联系方式" v-model="form.personPhonenumber" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="业务联系人：" prop="busName">
                <el-input placeholder="业务联系人" v-model="form.busName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务联系人电话：" prop="busPhonenumber">
                <el-input clearable placeholder="请输入业务联系人电话" v-model="form.busPhonenumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="公司邮箱：" prop="packageEmail">
                <el-input clearable placeholder="请输入公司邮箱" v-model="form.packageEmail" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="公司传真：" prop="packageFax">
                <el-input placeholder="请输入公司传真" v-model="form.packageFax" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-row>
                <el-form-item label="是否合格：" prop="isQualify">
                  <el-radio v-model="form.isQualify" :label="0">合格</el-radio>
                  <el-radio v-model="form.isQualify" :label="1">不合格</el-radio>
                </el-form-item>
              </el-row>
            </el-col>
          </el-row>
        </div>
        <!-- 财务信息 -->
        <div>
          <p class="pinformation">财务信息</p>
          <el-row>
            <el-col :span="14">
              <el-form-item label="纳税人识别号：" prop="taxpayerNumber">
                <el-input clearable placeholder="请输入纳税人识别号" v-model="form.taxpayerNumber" maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="银行账号：" prop="bankNumber">
                <el-input maxlength="100" clearable placeholder="请输入银行账号" v-model="form.bankNumber" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="7">
              <el-form-item label="开户行：" prop="bankName">
                <el-input placeholder="请输入开户行" v-model="form.bankName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="发票类型：">
                <el-select v-model="form.invoiceType" placeholder="请选择发票类型" clearable>
                  <el-option v-for="dict in sys_invoice_type" :key="parseInt(dict.value)" :label="dict.label"
                    :value="parseInt(dict.value)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发票点数（%）：" prop="invoiceCount">
                <el-input show-word-limit maxlength="2" placeholder="请输入发票点数（%）" v-model="form.invoiceCount" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <!-- 资质证书 -->
      <div>
        <div>
          <el-row>
            <p class="pinformation">资质情况</p>
            <p class="totalStyle">
              共 {{ sysOrgCertificateList.length }} 条数据
            </p>

            <el-row style="margin-bottom: 5px; margin-left: 20px">
              <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
            </el-row>
          </el-row>
        </div>
        <el-table :data="sysOrgCertificateList" v-loading="zsLoading" class="business" ref="subTableRef">
          <el-table-column label="证书名称" align="center" prop="certificateName" />
          <el-table-column label="证书编号" align="center" prop="certificateNumber" />
          <el-table-column label="开始时间" align="center" prop="startDate" />
          <el-table-column label="结束时间" align="center" prop="endDate" />
          <el-table-column label="当前状态" align="center" prop="status">
            <template #default="scope">
              <span v-if="scope.row.status == 0">正常</span>
              <span v-if="scope.row.status == 1">作废</span>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center">
            <template #default="scope">
              <span @click="proxy.downloadFile(scope.row.fileList, 1)" class="fileNameHover">{{
                scope.row.fileList ? scope.row.fileList[0].fileName : ""
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" type="index" width="270">
            <template #default="scope">
              <el-button link icon="View" @click="handleListView(scope.row)">查看</el-button>
              <el-button link icon="EditPen" @click="handleListEditor(scope.row)">编辑</el-button>
              <el-button link icon="Delete" @click="handleListDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新增修改弹出框 -->
    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" append-to-body draggable
      :close-on-click-modal="false">
      <el-form label-width="85px" :model="certificateForm" :disabled="disabled" :rules="certificateRules" ref="listRef">
        <el-form-item label="证书名称：" prop="certificateName">
          <el-input clearable placeholder="请输入证书名称" v-model="certificateForm.certificateName" maxlength="100" />
        </el-form-item>
        <el-form-item label="证书编号：">
          <el-input clearable placeholder="请输入证书编号" v-model="certificateForm.certificateNumber" maxlength="100" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间：">
              <el-date-picker v-model="certificateForm.startDate" placeholder="请输入开始时间" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间：">
              <el-date-picker placeholder="请输入结束时间" v-model="certificateForm.endDate" value-format="YYYY-MM-DD"
                type="date" @change="endDateChange" />
            </el-form-item>
          </el-col>

          <el-col :span="2" :offset="1">
            <el-checkbox label="永久" v-model="checkbox" @change="checkboxCheck" />
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态：" label-width="50px">
              <el-select placeholder="选择状态" clearable v-model="certificateForm.status">
                <el-option v-for="item in condition" :key="item.status" :label="item.name" :value="item.status" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件：" label-width="50px">
          <fileUpload v-model="certificateForm.fileList" :fileType="['doc', 'docx', 'pdf', 'jpg', 'png']"></fileUpload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="sava">保存</el-button>
          <el-button @click="Cancel" type="danger">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PackageOrg">
import {
  listOrg,
  addOrg,
  delOrg,
  getOrg,
  getPackageOrgList,
  addPackageOrgList,
  delPackageOrgList,
  editPackageOrgList,
} from "@/api/packageManage/packageOrg";
import City from "@/components/City/index.vue";

const { proxy } = getCurrentInstance();

const { sys_invoice_type } = proxy.useDict("sys_invoice_type");

const open = ref(false);
const title = ref("");
const orgTable = ref([]);
const total = ref(0);
const certificateForm = ref({ fileList: [] });
const disabled = ref(false);
const multiple = ref();
const ids = ref([]);
const areaRef = ref(null);
const highLightRow = ref(true);
const loading = ref(true);
const zsLoading = ref(false);
const checkbox = ref(true);

const condition = ref([
  { name: "正常", status: 0 },
  { name: "作废", status: 1 },
]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cityCode: -1,
    areaCode: -1,
    provinceCode: -1,
  },
  rules: {
    packageName: [
      { required: true, message: "分包方名称不能为空", trigger: "blur" },
    ],
    areaCode: [
      { required: true, message: "公司地区不能为空", trigger: "blur" },
    ],
    personPhonenumber: [
      {
        pattern: /^\d{11}$/,

        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    bankNumber: [{ pattern: /^([0-9 ])*$/, message: "请输入数字或者空格" }],
    busPhonenumber: [
      {
        pattern: /^\d{11}$/,

        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    packageEmail: [
      {
        pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
        message: "请输入正确的邮箱",
        trigger: "blur",
      },
    ],
    taxpayerNumber: [
      { pattern: /^([0-9a-zA-Z])*$/, message: "请输入数字或者字母" },
    ],
    invoiceCount: [{ pattern: /^([0-9])*$/, message: "请输入数字或者字母" }],
  },
  certificateRules: {
    certificateName: [
      { required: true, message: "证书名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules, certificateRules } = toRefs(data);

function handleAdd() {
  submitForm(true).then(() => {
    checkbox.value = true;
    disabled.value = false;
    open.value = true;
    title.value = "新增资质情况";
    certificateForm.value = { fileList: [], status: 0 };
    if (proxy.$refs["listRef"]) {
      proxy.$refs["listRef"].clearValidate();
    }
  });
}

function getList() {
  loading.value = true;
  listOrg(queryParams.value).then((res) => {
    orgTable.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

function submitForm(isAuto) {
  return new Promise((resolve, reject) => {
    proxy.$refs["orgRef"].validate((valid) => {
      if (valid) {
        addOrg(form.value).then((res) => {
          resolve();
          if (form.value.packageId) {
            if (!isAuto) proxy.$modal.msgSuccess("编辑成功");
            getList();
          } else {
            form.value.packageId = res.data;
            if (!isAuto) proxy.$modal.msgSuccess("新增成功");
            heightBright.value = res.data;
            resetQuery();
          }
        });
      }
    });
  });
}

function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.packageId);
  multiple.value = selection.length;
}

function handleDelete(row) {
  const packageId = row.packageId || ids.value;
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      return delOrg(packageId);
    })
    .then(() => {
      handleAddOrg();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function reset() {
  queryParams.value = {
    packageName: null,
    cityCode: -1,
    areaCode: -1,
    provinceCode: -1,
  };
}

function resetQuery() {
  areaRef.value.resetArea();
  reset();
  handleQuery();
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleAddOrg() {
  zsLoading.value = false;
  highLightRow.value = false;
  heightBright.value = "";
  proxy.$refs["orgRef"].clearValidate();
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
  form.value = {};
  viewCity.value = {};
  sysOrgCertificateList.value = [];
}

function cityQueryParam(val) {
  if (val.id == "left") {
    queryParams.value = Object.assign(queryParams.value, val);
  } else if (val.id == "right") {
    form.value = Object.assign(form.value, val);
  }
}

function areaCode(val) {
  form.value.areaCode = val;
}

function sava() {
  proxy.$refs["listRef"].validate((valid) => {
    if (valid) {
      certificateForm.value.packageId = heightBright.value;
      addPackageOrgList(certificateForm.value).then((res) => {
        proxy.$modal.msgSuccess("保存成功");
        open.value = false;
        zsLoading.value = true;
        getPackageOrgList({ packageId: heightBright.value }).then((res1) => {
          sysOrgCertificateList.value = res1.data;
          zsLoading.value = false;
        });
      });
    }
  });
}

function Cancel() {
  open.value = false;
}

function handleListDelete(row) {
  disabled.value = false;
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(() => {
      delPackageOrgList(row.certificateId).then((res) => {
        proxy.$modal.msgSuccess("删除成功");
        zsLoading.value = true;
        getPackageOrgList({ packageId: heightBright.value }).then((res) => {
          sysOrgCertificateList.value = res.data;
          zsLoading.value = false;
        });
      });
    })
    .catch(() => { });
}

function handleListEditor(row) {
  editPackageOrgList(row.certificateId).then((res) => {
    certificateForm.value = res.data;
    if (certificateForm.value.endDate) {
      checkbox.value = false;
    } else {
      checkbox.value = true;
    }
    disabled.value = false;
    open.value = true;
    title.value = "编辑资质情况";
    nextTick(() => {
      if (proxy.$refs["listRef"]) {
        proxy.$refs["listRef"].clearValidate();
      }
    });
  });
}

function handleListView(row) {
  editPackageOrgList(row.certificateId).then((res) => {
    certificateForm.value = res.data;
    if (certificateForm.value.endDate) {
      checkbox.value = false;
    } else {
      checkbox.value = true;
    }
    disabled.value = true;
    open.value = true;
    title.value = "查看资质情况";
    nextTick(() => {
      if (proxy.$refs["listRef"]) {
        proxy.$refs["listRef"].clearValidate();
      }
    });
  });
}

const viewCity = ref({});
const sysOrgCertificateList = ref([]);

function rowClick(row) {
  proxy.$refs["orgRef"].clearValidate();
  form.value = {};
  getOrg(row.packageId).then((res) => {
    form.value = res.data;
    heightBright.value = row.packageId;
    viewCity.value = {
      areaCode: res.data.areaCode,
      provinceCode: res.data.provinceCode,
      cityCode: res.data.cityCode,
    };
  });
  zsLoading.value = true;
  getPackageOrgList({ packageId: row.packageId }).then((res) => {
    sysOrgCertificateList.value = res.data;
    zsLoading.value = false;
  });
}

function checkboxCheck() {
  delete certificateForm.value.endDate;
}

function endDateChange() {
  checkbox.value = false;
}

getList();

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [
        { tableName: "main", bottomHeight: 73 },
        { tableName: "sub", bottomHeight: 25 },
      ];
    } else {
      heightParams.value = [
        { tableName: "main", bottomHeight: 22 },
        { tableName: "sub", bottomHeight: 25 },
      ];
    }
    getTableHeight();
  }
);

const heightParams = ref([
  { tableName: "main", bottomHeight: 22 },
  { tableName: "sub", bottomHeight: 25 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.packageId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}
</script>

<style></style>
